import type { FillStrategy } from '@/types.ts';
import { ElementInputStrategy } from '@/strategies/ElementStrategy.ts';
// import { AntDInputStrategy } from '@/strategies/AntDInputStrategy';
// import { NaiveInputStrategy } from '@/strategies/NaiveInputStrategy';

export class FormFiller {
  private strategies: FillStrategy[] = [];

  constructor() {
    this.strategies.push(
      new ElementInputStrategy(),
      // new AntDInputStrategy(),
      // new NaiveInputStrategy()
    );
  }

  public fillForm(data: Record<string, any>, root: HTMLElement = document.body) {
    for (const [labelText, value] of Object.entries(data)) {
      const field = this.findFieldByLabelText(labelText, root);
      if (field) {
        this.fillField(field, value);
      } else {
        console.warn(`无法找到表单字段: ${labelText}`);
      }
    }
  }

  private fillField(el: HTMLElement, value: any) {
    for (const strategy of this.strategies) {
      if (strategy.canHandle(el)) {
        strategy.fill(el, value);
        return;
      }
    }
    console.warn('No fill strategy matched for element:', el);
  }

  private findFieldByLabelText(labelText: string, root: HTMLElement): HTMLElement | null {
    const labels = Array.from(root.querySelectorAll('label, .form-label'));
    for (const label of labels) {
      if (label.textContent?.trim().includes(labelText)) {
        const input = label.closest('.form-item')?.querySelector('input, textarea, div');
        if (input) return input as HTMLElement;
      }
    }
    return null;
  }
}
